import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
const store = () => new Vuex.Store({
  state: {
    isLogin:false,//判断是否登录
    token:null,//session访问控制
    user: null //如果为空，则会中间件控制跳转404
  },
  mutations: {
    /*setToken (state, token) {
      state.token = token;
      if(token){
        state.isLogin=true;
      }else{
        state.isLogin=false;
      }
    },*/
    setUser (state, user) {
      if(user){
        state.user = user.username
        state.token = user.wapkey
        state.isLogin = true
      }else{
        state.user = state.token = null;
        state.isLogin = false
      }
    }
  },
  actions:{
    nuxtServerInit({ commit }, { req }) {
      if (req.session && req.session.authUser) {
        commit('setUser', req.session.authUser)
      }
    },
    async login({ commit }, { username, password }) {
      try {
        const { data } = await axios.post('/api/login', { username, password })
        commit('setUser', data)
      } catch (error) {
        if (error.response && error.response.status === 401) {
          throw new Error('Bad credentials')
        }
        throw error
      }
    },
    async logout({ commit }) {
      await axios.post('/api/logout')
      commit('setUser', null)
    }
  }
})

export default store